//
//  MTClubActivityDetailMemberCell.swift
//  MT
//
//  Created by ooops on 2020/1/1.
//  Copyright © 2020 张强. All rights reserved.
//

import Foundation
import Eureka
import MTCategory

@objc public protocol MTClubActivityDetailMemberCellDelegate: NSObjectProtocol {
    @objc optional func clickMoreButton(clickButton button: UIButton)
    @objc optional func clickAddCell()
    @objc optional func clickRemoveCell()
    @objc optional func didSelectCell(indexPath: IndexPath)
    @objc optional func didSelectCell(userName: String)
}

public class MTClubActivityDetailMemberCell: Cell<String>, CellType {
    
    weak var delegate: MTClubActivityDetailMemberCellDelegate?
    
    var group: JMSGGroup!
    private lazy var moreButton: UIButton = UIButton()
    fileprivate var count = 0
    fileprivate var sectionCount = 0
    /// 俱乐部活动用户
    var users: [JMSGUser?] = [] {
        didSet {
            _getData()
        }
    }
    /// 是否俱乐部活动发起者
    fileprivate var isGroupActivitityInitiator = false
    /// 是否已经加入了俱乐部活动, 加入俱乐部活动的人, 可以邀请其他俱乐部成员参加活动
    var isJoinGroupActivitity = false {
        didSet {
            _getData()
        }
    }
    fileprivate var currentUserCount = 0
    
    private lazy var flowLayout: UICollectionViewFlowLayout = {
        let flowLayout = UICollectionViewFlowLayout()
        let marginLR: CGFloat = 52
        let spacing: CGFloat = 8
        let items: CGFloat = 5
        let itemWidth: CGFloat = CGFloat((ScreenWidth - marginLR * 2 - (items - 1) * spacing) / items)
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = spacing
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
        flowLayout.minimumLineSpacing = 0
        return flowLayout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(MTClubDetailAvatorCell.self, forCellWithReuseIdentifier: MTClubDetailAvatorCell.reuseIdentity())
        collectionView.isScrollEnabled = false
        collectionView.backgroundColor = UIColor.clear
        return collectionView
    }()
    
    override public func setup() {
        super.setup()
        self.backgroundColor = UIColor.theme.background
        self.selectionStyle = .none
        self.height = { UITableView.automaticDimension }
        _init()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
            //.addObserver(self, selector: #selector(_updateGroupInfo), name: NSNotification.Name(rawValue: kUpdateGroupInfo), object: nil)
    }
    
    override public func update() {
        super.update()
        //_getData()
        let showMore = isGroupActivitityInitiator ? count > 13 : count > 14
//        let showMore = isGroupActivitityInitiator ? count > 1 : count > 1
        moreButton.isHidden = !showMore
        
        if isGroupActivitityInitiator {
            if count > 8 {
//                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 260))
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(270).priority(.high)
                }
            } else if count > 3 {
//                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 200))
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(200).priority(.high)
                }
            } else {
//                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 100))
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(180).priority(.high)
                }
            }
        } else {
            if count > 9 {
                //addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 260))
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(270).priority(.high)
                }
            } else if count > 4 {
//                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 200))
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(200).priority(.high)
                }
            } else {
//                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 100))
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(180).priority(.high)
                }
            }
        }
    }
    
    
    
    private func _init() {
        moreButton.isHidden = true
        addSubview(collectionView)
        
        moreButton.addTarget(self, action: #selector(_clickMore), for: .touchUpInside)
        moreButton.setTitleColor(UIColor.redpack.x5d5d5d, for: .normal)
        moreButton.titleLabel?.font = PingFangSCRegularFont(14)
        moreButton.setTitle("查看更多成员 >", for: .normal)
        self.addSubview(moreButton)
        
        moreButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(26)
            make.bottom.equalToSuperview().offset(-14)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(52)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(32)
            make.height.equalTo(180).priority(.high)
            make.bottom.equalToSuperview()//.offset(-52)
        }
            
//            addConstraint(_JCLayoutConstraintMake(collectionView, .left, .equal, self, .left, 15))
//            addConstraint(_JCLayoutConstraintMake(collectionView, .right, .equal, self, .right, -15))
//            addConstraint(_JCLayoutConstraintMake(collectionView, .top, .equal, self, .top))
//            if isGroupActivitityInitiator {
//                if count > 8 {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 260))
//                    collectionView.snp.updateConstraints { (make) in
//                        make.height.equalTo(270).priority(.high)
//                    }
//                } else if count > 3 {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 200))
//                    collectionView.snp.updateConstraints { (make) in
//                        make.height.equalTo(200).priority(.high)
//                    }
//                } else {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 100))
//                    collectionView.snp.updateConstraints { (make) in
//                        make.height.equalTo(180).priority(.high)
//                    }
//                }
//            } else {
//                if count > 9 {
//                    //addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 260))
//                    collectionView.snp.updateConstraints { (make) in
//                        make.height.equalTo(270).priority(.high)
//                    }
//                } else if count > 4 {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 200))
//                    collectionView.snp.updateConstraints { (make) in
//                        make.height.equalTo(200).priority(.high)
//                    }
//                } else {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 100))
//                    collectionView.snp.updateConstraints { (make) in
//                        make.height.equalTo(180).priority(.high)
//                    }
//                }
//            }
        }
        
        @objc func _clickMore() {
            delegate?.clickMoreButton?(clickButton: moreButton)
        }
        
        fileprivate func _getData() {
//            group.memberInfoList({ (result, error) in
//                if error == nil, let us = result as? [JMSGUser] {
//                    self.users = us
//                }
//            })
                //.memberArray()
            //self.users = group.memberArray()
            currentUserCount = users.count
            
            let user = JMSGUser.myInfo()
//    //        && group.ownerAppKey == user.appKey!  这里group.ownerAppKey == "" 目测sdk bug
            if group.owner == user.username  {
                isGroupActivitityInitiator = true
            }
            
            count = users.count
            
            if isGroupActivitityInitiator {
                if count > 13 {
                    currentUserCount = 13
                }
                if count > 8 {
                    sectionCount = 3
                } else if count > 3 {
                    sectionCount = 2
                } else {
                    sectionCount = 1
                }
            } else {
                if count > 14 {
                    currentUserCount = 14
                }
                if count > 9 {
                    sectionCount = 3
                } else if count > 4 {
                    sectionCount = 2
                } else {
                    sectionCount = 1
                }
            }
            self.collectionView.reloadData()
        }
}

extension MTClubActivityDetailMemberCell: UICollectionViewDataSource, UICollectionViewDelegate {
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionCount
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if isGroupActivitityInitiator {
            if section == 0 {
                return count >= 3 ? 5 : count + 2
            }
            if section == 1 {
                return  count >= 8 ? 5 : (count - 3)
            }
            return count >= 13 ? 5 : count - 8
        }
//        if section == 0 {
//            return count >= 4 ? 5 : count + 1
//        }
//        if section == 1 {
//            return  count >= 9 ? 5 : (count - 4)
//        }
        if section == 0 {
            return count >= 5 ? 5 : count
        }
        if section == 1 {
            return  count >= 10 ? 5 : (count - 5)
        }
        return count >= 14 ? 5 : count - 10
    }
    
//    func collectionView(_ collectionView: UICollectionView,
//                        layout collectionViewLayout: UICollectionViewLayout,
//                        sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
//        return CGSize(width:Int(collectionView.frame.size.width / 5), height: Int(collectionView.frame.size.height / CGFloat(sectionCount)))
//    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: MTClubDetailAvatorCell.reuseIdentity(), for: indexPath)
    }
    
    public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let cell = cell as? MTClubDetailAvatorCell else {
            return
        }
        let index = indexPath.section * 5 + indexPath.row
        if index == currentUserCount {
            cell.avator = UIImage(named: "button_zengjia")
            return
        }
        if index == currentUserCount + 1 {
            cell.avator = UIImage(named: "button_jianshao")
            return
        }
        if let user = users[index] {
            cell.bindDate(user: user)
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let index = indexPath.section * 5 + indexPath.row
        if index == currentUserCount {
            delegate?.clickAddCell?()
            return
        }
        if index == currentUserCount + 1 {
            delegate?.clickRemoveCell?()
            return
        }
        
        if let user = users[index] {
            delegate?.didSelectCell?(userName: user.username)
        }
        
        // delegate?.didSelectCell?(indexPath: indexPath)
    }
    
}


// The custom Row also has the cell: CustomCell and its correspond value
public final class MTClubActivityDetailMemberRow: Row<MTClubActivityDetailMemberCell>, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
        cellProvider = CellProvider<MTClubActivityDetailMemberCell>.init()
    }
}
